from PySide6.QtWidgets import *
from PySide6.QtCore import *
from PySide6.QtGui import QPixmap
from PySide6.QtUiTools import QUiLoader


class show_pet(QWidget):
    Signal_close = Signal()
    def __init__(self,parent=None):
        super().__init__(parent)
        self.db = self.parent().db
        self.pet_id = None

        loader = QUiLoader()
        self.ui = loader.load("ui/pet_info.ui",self)

        self.setLayout(QVBoxLayout(self))
        self.layout().addWidget(self.ui)
        self.layout().setContentsMargins(0, 0, 0, 0)

        with open('qss/style.qss', 'r', encoding='utf-8') as f:
            style = f.read()
            self.setStyleSheet(style)

    def set_pet_id(self,pet_id):
        self.pet_id = pet_id
        self.pet_info_show()
        self.pet_skill_show()
        self.pet_img_show()

# region 显示宠物图片
    def pet_img_show(self):
        pixmap = QPixmap(f"pet_img/{self.pet_id}.png")
        if not pixmap.isNull():
            label_height = 150
            scaled_pixmap = pixmap.scaledToHeight(label_height, Qt.SmoothTransformation)
            self.ui.lb_img.setPixmap(scaled_pixmap)
# endregion

# region 显示宠物信息
    def pet_info_show(self):
        pet_info = self.db.get_creature_by_id(self.pet_id)
        if pet_info:
              # 文本类型字段直接显示
            self.ui.lb_id.setText(str(pet_info.get('id', '0')))
            self.ui.lb_name.setText(pet_info.get('name', '未知'))
            self.ui.lb_attribute.setText(pet_info.get('attribute', '无属性'))
            self.ui.lb_passive_immunity.setText(pet_info.get('passive_immunity', '无免疫'))
            self.ui.lb_bloodline.setText(pet_info.get('bloodline', '普通系'))

            # 基础数值字段（当前值）
            self.ui.lb_hp.setText(f"{pet_info.get('hp', 0):,}")
            self.ui.lb_attack.setText(f"{pet_info.get('attack', 0):,}")
            self.ui.lb_defense.setText(f"{pet_info.get('defense', 0):,}")
            self.ui.lb_sp_attack.setText(f"{pet_info.get('sp_attack', 0):,}")
            self.ui.lb_sp_defense.setText(f"{pet_info.get('sp_defense', 0):,}")
            self.ui.lb_speed.setText(f"{pet_info.get('speed', 0):,}")
            self.ui.lb_total.setText(f"{pet_info.get('total', 0):,}")

            # 最大值显示部分
            self.ui.lb_hp_max.setText(f"{pet_info.get('hp_max', 0):,}")
            self.ui.lb_attack_max.setText(f"{pet_info.get('attack_max', 0):,}")
            self.ui.lb_defense_max.setText(f"{pet_info.get('defense_max', 0):,}")
            self.ui.lb_sp_attack_max.setText(f"{pet_info.get('sp_attack_max', 0):,}")
            self.ui.lb_sp_defense_max.setText(f"{pet_info.get('sp_defense_max', 0):,}")
            self.ui.lb_speed_max.setText(f"{pet_info.get('speed_max', 0):,}")
# endregion
# region 显示技能
    def pet_skill_show(self):
        """显示宠物技能 - 每次调用前清除旧内容"""
        if not hasattr(self.ui, "w_show_skill"):
            return
        
        # 清除旧内容
        w_show_skill = self.ui.w_show_skill
        
        # 1. 移除现有的滚动区域（如果存在）
        if w_show_skill.layout() is not None:
            # 获取并删除现有的布局
            old_layout = w_show_skill.layout()
            while old_layout.count():
                item = old_layout.takeAt(0)
                widget = item.widget()
                if widget:
                    # 移除滚动区域的内部部件
                    if isinstance(widget, QScrollArea):
                        scroll_widget = widget.widget()
                        if scroll_widget:
                            scroll_widget.deleteLater()
                    widget.deleteLater()
            # 清除布局引用
            old_layout.deleteLater()
            w_show_skill.setLayout(None)
        
        # 2. 确保容器存在
        if not w_show_skill:
            w_show_skill = QWidget()
            self.ui.w_show_skill = w_show_skill
            
        # 获取技能数据
        if not self.pet_id or not self.db:
            return
        
        pet_skills = self.db.get_pet_skills(self.pet_id)
        if not pet_skills:
            # 添加"无技能"提示
            w_show_skill.setLayout(QVBoxLayout())
            no_skill = QLabel("该宠物暂无技能数据")
            no_skill.setAlignment(Qt.AlignCenter)
            w_show_skill.layout().addWidget(no_skill)
            return
        
        # 创建网格布局
        grid = QGridLayout()
        grid.setColumnStretch(0, 1)   # 等级列
        grid.setColumnStretch(1, 2)   # 名称列
        grid.setColumnStretch(2, 2)   # 类型列
        grid.setColumnStretch(3, 1)   # 威力列
        grid.setColumnStretch(4, 1)   # PP列
        grid.setColumnStretch(5, 4)   # 描述列
        grid.setVerticalSpacing(20)
        grid.setHorizontalSpacing(5)

        # 创建标题行（第0行）
        titles = ["等级", "技能名称", "类型", "威力", "PP值", "技能描述"]
        for col, title in enumerate(titles):
            label = QLabel(title)
            label.setStyleSheet("""
                QLabel {
                    font-weight: bold; 
                    font-size: 18px;
                    color: #333;
                    border-bottom: 2px solid #666;
                    padding: 5px 0;
                }
            """)
            label.setFixedHeight(30)
            grid.addWidget(label, 0, col)

        # 添加技能数据（从第1行开始）
        for row, skill in enumerate(pet_skills, start=1):
            # 等级
            lbl_level = QLabel(skill['level'])
            lbl_level.setStyleSheet("font-size: 13px; color: #E67E22;")
            lbl_level.setAlignment(Qt.AlignCenter)
            grid.addWidget(lbl_level, row, 0)

            # 名称
            lbl_name = QLabel(skill['name'])
            lbl_name.setStyleSheet("font-size: 14px; color: #2C3E50; font-weight: 500;")
            lbl_name.setAlignment(Qt.AlignCenter)
            grid.addWidget(lbl_name, row, 1)

            # 类型
            lbl_type = QLabel(skill['type'])
            self._get_type_color(lbl_type, skill['type'])
            lbl_type.setStyleSheet(f"""
                padding: 2px 5px;
                border-radius: 4px;
                font-size: 14px;
            """)
            lbl_type.setAlignment(Qt.AlignCenter)
            grid.addWidget(lbl_type, row, 2)

            # 威力
            power_text = skill['power'] if skill['power'] != '无' else "--"
            lbl_power = QLabel(power_text)
            lbl_power.setStyleSheet("font-size: 13px; color: #27AE60;")
            lbl_power.setAlignment(Qt.AlignCenter)
            grid.addWidget(lbl_power, row, 3)

            # PP值
            lbl_pp = QLabel(str(skill['pp']))
            lbl_pp.setStyleSheet("font-size: 13px; color: #2980B9;")
            lbl_pp.setAlignment(Qt.AlignCenter)
            grid.addWidget(lbl_pp, row, 4)

            # 描述
            lbl_desc = QLabel(skill['description'])
            lbl_desc.setStyleSheet("font-size: 13px; color: #000000;")
            lbl_desc.setWordWrap(True)
            grid.addWidget(lbl_desc, row, 5)

        # 添加布局到容器
        container = QWidget()
        container.setLayout(grid)
        
        # 添加滚动区域
        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setWidget(container)
        
        # 设置新布局
        w_show_skill.setLayout(QVBoxLayout())
        w_show_skill.layout().addWidget(scroll)
        w_show_skill.layout().setContentsMargins(0, 0, 0, 0)

    def _get_type_color(self, label,skill_type: str) -> str:
        """根据技能类型返回对应的颜色"""
        attribute_map = {
            "草系": "grass",
            "火系": "fire",
            "水系": "water",
            "光系": "light",
            "土系": "earth",
            "石系": "stone",
            "冰系": "ice",
            "龙系": "dragon",
            "电系": "electric",
            "毒系": "poison",
            "虫系": "bug",
            "武系": "fighting",
            "翼系": "flying",
            "萌系": "cute",
            "幽灵": "ghost",
            "恶魔": "demon",
            "机械": "mechanical",
            "普通": "normal",
            "神火": "god_fire",
            "神草": "god_grass",
            "神水": "god_water",
            "无": "none"
        }   
        # 提取主类型
        if skill_type == "无":
            class_name = "none"
        else:
            main_type = skill_type[:2]  # 例如"火系魔法"取前两字
            class_name = attribute_map.get(main_type, "None")

        # 设置class属性（覆盖原有值）
        label.setAutoFillBackground(True)   
        label.setProperty("class", class_name)

        label.style().unpolish(label)
        label.style().polish(label)
        label.update()
# endregion
